package com.yyfax.ph.personal.authority.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import cn.jpush.android.api.JPushInterface;
import com.yyfax.common.CLog;
import com.yyfax.common.parse.JsonMananger;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceManager;
import com.yyfax.ph.common.widgets.shortbadger.ShortcutBadger;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.gesture.ValidateGesturesActivity;
import com.yyfax.ph.personal.bindapply.BindApplyActivity;
import com.yyfax.ph.personal.message.MessageActivity;
import com.yyfax.ph.personal.mymoney.cash.CashActivity;

public class PushInfoReceiver extends BroadcastReceiver {
	private static final String TAG = PushInfoReceiver.class.getSimpleName();

	private static final int PROCESS_PUSH_MESSAGE = 1;
	public static final String FROM_PUSH_FLAG = "fromPushFlag";

	private Context mContext;

	@Override
	public void onReceive(Context ctx, Intent intent) {
		mContext = ctx;
		Bundle bundle = intent.getExtras();
		String action = intent.getAction();

		if (JPushInterface.ACTION_REGISTRATION_ID.equals(action)) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_J_PUSH_REGISTER_ID, regId);
			CLog.i(TAG, "接收Registration Id : " + regId);
		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(action)) {
			String msg = bundle.getString(JPushInterface.EXTRA_MESSAGE);
			CLog.i(TAG, "接收到推送下来的自定义消息:" + msg);
		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(action)) {
			/***
			 * 增加处理  如果未登录 还是收到极光的消息 不处理
			 */
			if (!YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
				return;
			}
			EventAgent.post(new PushEvent(false));

			//收到一条推送消息角标加1
			int unReadCount = YJPH.getInstance().getPreferenceManager().getUnreadMsgCount();
			unReadCount = unReadCount + 1;
			YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_UNREAD_PUSH_MESSAGE_COUNT, unReadCount);
			ShortcutBadger.applyCount(ctx, unReadCount);

			int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			CLog.i(TAG, "接收到推送下来的通知的ID: " + notificationId);
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(action)) {
			/***
			 * 增加处理  如果未登录 还是收到极光的消息 不处理
			 */
			if (!YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
				return;
			}
			//点击消息角标减1
			int unReadCount = YJPH.getInstance().getPreferenceManager().getUnreadMsgCount();
			if (unReadCount == 0) {
				ShortcutBadger.removeCount(ctx);
			} else if (unReadCount > 0) {
				unReadCount = unReadCount - 1;
				ShortcutBadger.applyCount(ctx, unReadCount);
			}
			YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_UNREAD_PUSH_MESSAGE_COUNT, unReadCount);
			bundleFilter(bundle);
			CLog.i(TAG, "用户点击打开了通知");
		} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(action)) {
			CLog.i(TAG, "用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
		} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(action)) {
			boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
			CLog.i(TAG, action + " connected state change to " + connected);
		} else {
			CLog.i(TAG, "Unhandled intent - " + action);
		}
	}

	// 解析所有的 intent extra 数据
	private void bundleFilter(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		String title = "";
		String content = "";
		String jumpUrl = "";
		String pushType = "1";//推送类型(默认1：文本类型)
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
				try {
					if (key.equals("cn.jpush.android.NOTIFICATION_CONTENT_TITLE")) {
						//推送的标题
						title = bundle.getString(key);
					} else if (key.equals("cn.jpush.android.ALERT")) {
						//推送的信息
						content = bundle.getString(key);
					} else if (key.equals("cn.jpush.android.EXTRA")) {
						String jsonData = bundle.getString(key);
						if (!TextUtils.isEmpty(jsonData)) {
							processReceivedPushMessage(jsonData);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void processReceivedPushMessage(final String result) {
		GlobalVariableConfig.getExecutorService().execute(new Runnable() {
			@Override
			public void run() {
				PushMessage msg;
				try {
					msg = JsonMananger.jsonToBean(result, PushMessage.class);
					CLog.i(TAG, "result = " + result);
					if (null != msg) {
						handler.obtainMessage(PROCESS_PUSH_MESSAGE, msg).sendToTarget();
					}
				} catch (Exception e) {
					CLog.i(TAG, "解析推送消息失败");
					e.printStackTrace();
				}
			}
		});
	}

	private Handler handler = new Handler(Looper.myLooper()) {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == PROCESS_PUSH_MESSAGE) {
				PushMessage pushMessage = (PushMessage) msg.obj;
				processMessage(pushMessage);
			}
		}
	};

	private void processMessage(PushMessage msg) {
		Intent intent = new Intent();
		String targetClass = null;
		switch (msg.target) {
			case 0://消息页面
				YJPH.getInstance().clearJPush();
				targetClass = MessageActivity.class.getName();
				break;
			case 1://进度查询页面
				targetClass = MainActivity.class.getName();
				break;
			case 2://返现明细页面
				targetClass = CashActivity.class.getName();
				break;
			case 3://子账户申请绑定页面
				targetClass = BindApplyActivity.class.getName();
				break;
		}
		//应对后面可能增加的target类型，targetClass可能为null
		if (TextUtils.isEmpty(targetClass)) {
			return;
		}
		intent.setClassName(mContext, targetClass);
		intent.putExtra(FROM_PUSH_FLAG, true);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PreferenceManager pm = YJPH.getInstance().getPreferenceManager();
		//是否需要手势密码解锁
		if(pm.isNeedValidateGesture()){
			ValidateGesturesActivity.start(mContext, intent);
		}else{
			mContext.startActivity(intent);
		}

	}

	public static class PushMessage {
		public int type;//type:0 app内页面1 wap页面
		public String userId;
		public int target;//target目标页面编号 0:消息页面 1:进度查询页面 2:返现明显页面 3:子账户申请绑定页面
	}
}
